package utils

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"server/config"
)

type WxLoginRes struct {
	OpenId     string `json:"openid"`
	SessionKey string `json:"sessionKey"`
	Unionid    string `json:"unionid"`
	Errcode    int    `json:"errcode"`
	Errmsg     string `json:"errmsg"`
}

func WxLogin(code string, wxApplet config.WxApplet) (*WxLoginRes, error) {
	url := fmt.Sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=%s",
		wxApplet.LoginUrl, wxApplet.Appid, wxApplet.Secret, code, wxApplet.GrantType)
	response, err := http.Get(url)
	wxLoginRes := new(WxLoginRes)
	resData, err := io.ReadAll(response.Body)
	err = json.Unmarshal(resData, wxLoginRes)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("微信登录失败,err:%s,wxloginResError:%s", err.Error(), wxLoginRes.Errmsg))
	}
	if wxLoginRes.Errcode != 0 {
		return nil, errors.New(fmt.Sprintf("微信登录失败,wxloginResError:%s", wxLoginRes.Errmsg))
	}
	return wxLoginRes, nil
}
